<?php

namespace App\Http\Controllers\Admin;

use App\Models\Goods;
use App\Models\GoodsOrder;
use App\Models\GoodsOrderAddress;
use App\Validate\GoodsValidate;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * 商品兑换记录
 */
class GoodsRecordController extends CommonController
{
    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new GoodsOrder();
        $this->validate = new GoodsValidate();
    }

    /**
     * 用户商品兑换记录
     * @param page int 当前页
     * @param limit int 分页大小
     * @param send_way int 兑换方式(1 自提 2 邮递  3、2者都可以)
     * @param start_time datetime 创建时间范围搜索(开始)
     * @param end_time datetime 创建时间范围搜索(结束)
     * @param type_id int 商品类型id
     * @param status int 订单状态 1 待领取  2已取走（自提） 3待发货  4已发货 （邮递）  5 已过期   6 已取消
     * @param keywords string 搜索关键词
     * @param keywords_type int 搜索关键词类型 1 订单号  2 商品名   3 姓名  4 读者证号  5 兑换码
     */
    public function lists()
    {
        $this->model->checkOrderStatus(); //处理已过期的订单
        $this->model->checkNoPayOrder(); //获取未支付的订单，判断是否过期，修改状态


        $app_goods_expire_time = config('other.app_goods_expire_time');
        if ($app_goods_expire_time && $app_goods_expire_time < date('Y-m-d')) {
            $app_goods_expire_msg = config('other.app_goods_expire_msg') ? config('other.app_goods_expire_msg') : '试用已过期！';
            return $this->returnApi(202, $app_goods_expire_msg); //使用过期，什么都不能使用
        }

        $limit = $this->request->input('limit', 10);
        $page = $this->request->input('page', 10);
        $send_way = $this->request->send_way;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $type_id = $this->request->type_id;
        $status = $this->request->status;
        $keywords = $this->request->keywords;
        $keywords_type = $this->request->keywords_type;

        $res = $this->model->lists($keywords, $keywords_type, $type_id, $status, $send_way, $start_time, $end_time, $limit);

        if ($res['data']) {
            $res = $this->disPageData($res);
            $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 领取
     * @param id 兑换记录id
     */
    public function fetchGoods()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('fetch')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }

        DB::beginTransaction();
        try {
            $res = $this->model->fetchGoods($this->request->id);
            $goods_name = Goods::where('id', $res->goods_id)->value('name');
            //推送系统消息
            $system_id = $this->systemAdd('兑换商品领取成功提醒', $res->user_id, $res->account_id, 13, $res->id, '您兑换的商品：【' . $goods_name . '】已领取成功');

            DB::commit();
            return $this->returnApi(200, '领取成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }


    /**
     * 确认发货
     * @param id int 兑换记录id
     * @param tracking_number string 快递运单号
     */
    public function sendGoods()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('send')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }

        DB::beginTransaction();
        try {
            $res = $this->model->sendGoods($this->request->id, $this->request->tracking_number);
            $goodsOrderAddressObj = new GoodsOrderAddress();
            $goodsOrderAddressObj->sendGoodsSaveAddress($this->request->id); //修改商品兑换发货地址
            $goods_name = Goods::where('id', $res->goods_id)->value('name');
            //推送系统消息
            $system_id = $this->systemAdd('兑换商品发货成功提醒', $res->user_id, $res->account_id, 13, $res->id, '您兑换的商品：【' . $goods_name . '】已发货成功，请及时关注邮递信息');

            DB::commit();
            return $this->returnApi(200, '领取成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }


    /**
     * 商品取消兑换
     * @param $id  订单id
     * @param $refund_remark  取消兑换理由  最少  5个 字
     */
    public function cancelConversionGoods()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('cancel_conversion')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $order_id = $this->request->id;
        $refund_remark = $this->request->refund_remark;

        //限制用户多次点击
        $key = md5('goods_cancel_conversion' . $order_id . request()->ip());
        $oldKey =  Cache::get($key); //没有缓存返回false
        if ($oldKey) {
            return $this->returnApi(201, "您操作的太频繁了，请稍后重试");
        } else {
            Cache::put($key, 1, 3);
        }

        $res = $this->model->where('id', $order_id)->first();
        if (empty($res)) {
            return $this->returnApi(202, '网络错误');
        }
        if ($res->status != 1 && $res->status != 3) {
            return $this->returnApi(202, '网络错误');
        }
        //允许在取消期限过去一个月也可以取消
        if ($res->cancel_end_time < date('Y-m-d H:i:s', strtotime('-30 day'))) {
            return $this->returnApi(202, '此商品不允许取消');
        }

        DB::beginTransaction();
        try {
            $res = $this->model->where('id', $order_id)->lockForUpdate()->first();
            //增加一个取消的理由
            $res->refund_remark = $refund_remark;
            $res->change_time = date('Y-m-d H:i:s');
            $res->status = 6;
            $res->save();

            Goods::where('id', $res->goods_id)->decrement('has_number');

            //用户积分操作  与 系统消息
            $system_id = $this->systemAdd("管理员取消商品兑换", $res->user_id, $res->account_id, 8, $res->id, '取消商品兑换成功，返还兑换商品扣除的 ' . $res->score . ' 积分');

            $scoreRuleObj = new \App\Http\Controllers\ScoreRuleController();
            $scoreRuleObj->scoreGoodReturn($res->score, $res->user_id, $res->account_id, '管理员取消商品兑换', '取消商品兑换成功', $system_id); //添加积分消息

            DB::commit();
            return $this->returnApi(200, '取消兑换成功', true);
        } catch (\Exception $e) {
            //var_dump($e);exit;
            $msg = $e->getCode() == 2002 ? $e->getMessage() : '取消兑换失败';
            DB::rollBack();
            return $this->returnApi(202,  $msg);
        }
    }
}
